package com.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Websocket 聊天服务器-服务端
 * 
 * @author waylau.com
 * @date 2015-3-7
 */
public class WebSocketServer implements Runnable{

    private int port;
    private Class webSocketHandler;
    private Logger logger = LogManager.getLogger("[netty]"+getClass().getName());

    public WebSocketServer(int port,Class webSocketHandler) {
        this.port = port;
        this.webSocketHandler=webSocketHandler;
    }

    public void run() {
        EventLoopGroup bossGroup=null; // (1)
        EventLoopGroup workerGroup=null;
        try {
            bossGroup = new NioEventLoopGroup(); // (1)
            workerGroup = new NioEventLoopGroup();

            ServerBootstrap serverBootstrap = new ServerBootstrap(); // (2)
            serverBootstrap.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new WebSocketInitializer(webSocketHandler))  //(4)
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            logger.debug("WebSocketServer 启动了" + port+" "+webSocketHandler.getName());
    		
            // 绑定端口，开始接收进来的连接
            ChannelFuture channelFuture; // (7)
            try {
                channelFuture = serverBootstrap.bind(port).sync();
                // 等待服务器  socket 关闭 。
                // 在这个例子中，这不会发生，但你可以优雅地关闭你的服务器。
                channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            if(workerGroup!=null) workerGroup.shutdownGracefully();
            if(bossGroup!=null) bossGroup.shutdownGracefully();

            logger.debug("WebSocketServer 关闭了"+" "+webSocketHandler.getName());
        }
    }
}